<template>
  <div class="chart-content">
    <div v-if="chartDataEmpty" class="operator-chart-empty">
      <img alt="" src="@/assets/view/empty2.png" />
      暂无图表数据
    </div>
    <div v-else id="line-chart-id"></div>
  </div>
</template>

<script lang="ts">
/**
 * 经济类算子节点 - 数据平滑图表
 */
import { Component, Vue, Watch } from 'vue-property-decorator'
import DataStore from '@/store/modules/dataview'
import { LineChart } from '@zjlabvis/vis-charts'

@Component({
  components: {},
})
export default class DataSmoothingChart extends Vue {
  private chartData: any[] = [] // 图表数据
  public chartDataEmpty: boolean = false // 空数据
  public compInstance: any = ''
  public yAxisAttribute: string[] = []

  // 图表数据
  public get getQueryDataVis() {
    return DataStore.getQueryDataVis || {}
  }

  public get commonConfig() {
    return {
      value: this.chartData,
      labelKey: 'x',
      labelIsShow: false,
      labelTextMaxlength: 4,
      xAxisAttribute: 'x',
      yAxisAttribute: this.yAxisAttribute,
      xAxisGridIsShow: false,
      xAxisFontSize: 12,
      legendPosition: 'top-left',
    }
  }

  @Watch('getQueryDataVis', { deep: true })
  private watchChartResult() {
    if (this.compInstance && !this.chartDataEmpty) {
      this.compInstance.destroy()
    }
    if (this.getQueryDataVis.data) {
      this.chartDataEmpty = false
      this.$nextTick(() => {
        this.init()
      })
    } else {
      this.chartDataEmpty = true
      this.compInstance = ''
    }
  }

  public async init() {
    const { data, head } = this.getQueryDataVis
    this.chartDataEmpty = head.length === 0
    if (head.length > 0) {
      this.yAxisAttribute = head.map((item: any, index: number) => {
        if (index === 0) {
          return `${item.name} (平滑前)`
        }
        return `${item.name} (平滑后)`
      })
      this.chartData = []
      const chartData: any[] = []
      data.forEach((element: any) => {
        const item: any = {
          x: `${element[0]}`,
          [this.yAxisAttribute[0]]: element[1],
          [this.yAxisAttribute[1]]: element[2],
        }
        chartData.push(item)
      })
      this.chartData = chartData
      this.compInstance = new LineChart('line-chart-id', this.commonConfig)
    }
  }
}
</script>

<style lang="less" scoped>
@import '@/styles/scroll-bar';

.chart-header {
  display: flex;
  height: 38px;
  justify-content: space-between;
  line-height: 38px;
  width: 100%;
}

.chart-content {
  background: #fff;
  padding: 8px 20px;
  width: 100%;

  .operator-chart-empty {
    align-items: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
</style>
